package client;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoginPanel extends JPanel{
    private static final long serialVersionUID = 1L;

    Client client;
	JButton submitButton;
	JTextField username;
	JTextField password;
	
	public String validUsername = "user";
	public String validPassword = "test123";
	
	public LoginPanel(Client client){
		this.client = client;
		
		// Self setup
		this.setBorder(BorderFactory.createLineBorder(Color.gray, 2));
		this.setLayout(null);
		
		// Panel setup
		JPanel linePanel = new JPanel();
		linePanel.setBorder(BorderFactory.createMatteBorder(15, 15, 15, 15, Color.white));
        linePanel.setBackground(Color.white);
        linePanel.setLayout(new GridLayout(3,2,5,5));
		linePanel.setBounds(2,2,196, 96);
		
		// Create elements
		username = new JTextField();
	    password = new JPasswordField();
	    submitButton = new JButton("Submit");
		
		// Assemble
		linePanel.add(new JLabel("Username :"));
		linePanel.add(username);
		linePanel.add(new JLabel("Password :"));
		linePanel.add(password);
		linePanel.add(new JLabel(""));
		linePanel.add(submitButton);
		this.add(linePanel);
		
		// Add listeners
		username.addActionListener(new SubmitAction());
		password.addActionListener(new SubmitAction());
		submitButton.addActionListener(new SubmitAction());
	}
	
	private class SubmitAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
		    if(!validateCredentials()) {
		        JOptionPane.showMessageDialog(client.frame, "The username/password combination provided is invalid.", "Invalid credentials", JOptionPane.ERROR_MESSAGE);
		        if(client.state == Client.State.LOGIN) {
		            clearBoth();
		        } else {
		            clearPass();
		        }
		        return;
		    }
		    
		    // If loggin in, ask to save usage.
			if(client.state == Client.State.LOGIN){
				JOptionPane.showConfirmDialog(client.frame, 
						"Welcome to CyberPub!!\n" +
						"\n" +
						"We would like to save your usage data for\n" +
						"statistic purpose. This is completely anonymous\n" +
						"Do you accept?",
						"Welcome", JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE);
			}
			client.login();
		}
	}
	
	public void clearBoth() {
	    this.username.setText("");
	    this.password.setText("");
	}
	
	public void clearPass() {
	    this.password.setText("");
	}
	
	private boolean validateCredentials() {
	    return this.username.getText().equals(this.validUsername) && this.password.getText().equals(this.validPassword);
	}

}
